import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { getMemberAddressAPI } from '@/services/address'

// 定义 Store
export const useAddressStore = defineStore(
  'address',
  () => {
    // 获取收货地址列表数据
    const addressList = ref([])

    //默认地址
    const defaultAddress = ref(null)

    const getMemberAddressData = async () => {
      const res = await getMemberAddressAPI()
      addressList.value = res.result
    }

    // 改变默认地址
    const changeAddress = (index, item) => {
      defaultAddress.value = index
      selectedAddress.value = item
    }

    //计算默认地址
    const address = computed(() => {
      return selectedAddress.value || addressList.value[defaultAddress.value] || '请选择收货地址'
    })

    const selectedAddress = ref()
    const changeSelectedAddress = (val) => {
      selectedAddress.value = val
    }

    // 记得 return
    return {
      addressList,
      getMemberAddressData,
      defaultAddress,
      changeAddress,
      address,
      changeSelectedAddress,
    }
  },
  {
    // 配置持久化
    persist: {
      // 调整为兼容多端的API
      storage: {
        setItem(key, value) {
          uni.setStorageSync(key, value)
        },
        getItem(key) {
          return uni.getStorageSync(key)
        },
      },
    },
  },
)
